import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { CreateSceneBondScriptDto } from './dto/create-scene_bond_script.dto';
import { SceneBondScript } from './entities/scene_bond_script.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { WINSTON_LOGGER_TOKEN } from 'src/winston/winston.module';
import { UpdateSceneBondScriptDto } from './dto/update-scene_bond_script.dto';

@Injectable()
export class SceneBondScriptService {
  constructor(
    @InjectRepository(SceneBondScript)
    private readonly sceneBondScriptRepository: Repository<SceneBondScript>,
  ) {}

  @Inject(WINSTON_LOGGER_TOKEN)
  private logger;

  async createBond(createSceneBondScriptDto: CreateSceneBondScriptDto) {
    const insert = this.sceneBondScriptRepository.create(
      createSceneBondScriptDto,
    );
    const res = await this.sceneBondScriptRepository.insert(insert);
    return res.raw[0].id;
  }
  getBondByScriptuuid(scriptuuid: string) {
    return this.sceneBondScriptRepository.findOne({
      where: { script_id: scriptuuid },
    });
  }
  getBondBySceneuuid(sceneuuid: string) {
    return this.sceneBondScriptRepository.findOne({
      where: { scene_id: sceneuuid },
    });
  }
  async updateBond(id: string,updateSceneBondScriptDto:UpdateSceneBondScriptDto) {
    const oldBond = await this.sceneBondScriptRepository.findOne({
      where: { id: id },
    });
    if (!oldBond) {
      return '未找到匹配的记录，没有进行更新操作';
    }
    try {
      const updateFolder = this.sceneBondScriptRepository.merge(
        oldBond,
        updateSceneBondScriptDto,
      );
      await this.sceneBondScriptRepository.save(updateFolder);
      return '修改文件夹属性成功!';
    } catch (err) {
      this.logger.error(
        `更新文件夹属性失败${err}`,
        `${SceneBondScriptService.name}-${this.updateBond.name}`,
      );
      throw new BadRequestException('更新文件夹属性失败');
    }
  }
  async deleteBond(id: string) {
    const result = await this.sceneBondScriptRepository.delete({
      id: id,
    });
    if (result.affected && result.affected > 0) {
      return `成功删除 ${result.affected} 条记录`;
    } else {
      return `未找到匹配的记录，没有进行删除操作`;
    }
  }
}
